$(document).ready(function(){
        //handles ctrl-s 
	$(document).keydown(function(event) {
		var currKey=0,e=e||event; 
		currKey=e.keyCode||e.which||e.charCode;  //do this handle FF and IE
		if (!( String.fromCharCode(event.which).toLowerCase() == 's' && event.ctrlKey) && !(event.which == 19)) return true;
			event.preventDefault();
			openSaveDialog();
			return false;
	});
        //organize orgchart from db
        setOrgchart();
})
//for showing the modal in choosing the users
function showModal(container,subtitle,userType,type,appendType){
        var node_id = $("#node_id").val();
        if(node_id!=""){
                $(container).dialog({
                        height:300,
                        width:320,
                        modal:true,
                        resizable:false
                });
                $(".orgchartUserTitle").text("Choose "+subtitle+" of the Department")
                $("#txtorgchartDeptUsers").val(userType);
                $(".userDepartment").attr("type",type)
                $(".userDepartment").attr("appendType",appendType)
                /* ORGCHART Users list*/
                containertype = $(".userDepartment").attr("type");
                //remove the elements in the modal
                $(".userDepartment").html(null)
                getUsersForDepartment(containertype,userType)
        }else{
                alert("Please activate node..")
        }
}
//get company users
function getUsersForDepartment(containertype,userType){
        $.ajax({
        url: url + "loadUsersForDepartment/",
        cache: false
        }).done(function( data ) {
		users = data.split(",");
		display = "";
		activeDept = $(".nodeDepartment").val();
		//get all the users in the node
		$(".outerNode").each(function(){
			//get the json(head,assistant head and  members)
                        if($(this).attr("node_data")!=""){
                                var node_data =  jQuery.parseJSON($(this).attr("node_data"));
                                dept = node_data['dept'];
                                head = node_data['orgChartHead'].substr(0,node_data['orgChartHead'].length-1);
                                assistant = node_data['orgChartAsstHead'].substr(0,node_data['orgChartAsstHead'].length-1);
                                members = node_data['orgChartMembers'].split(","); //split the members to get specific
                                //extract the users from database
                                for(var a=0;a<users.length-1;a++){
                                        userId = users[a].split("->")[0];
                                        userText = users[a].split("->")[1];
                                        userSelected = users[a].split("->")[2];
                                        //check if users is exist in the node
                                        if(users[a]==head){
                                                if(activeDept==dept && userType=="orgChartHead"){
                                                        //set the choice checked
                                                        users.splice(a,1,userId+"->"+userText+"->1");
                                                }
                                                if(userType!="orgChartHead" || activeDept!=dept){
                                                        //replace the value to empty
                                                        users.splice(a,1,"");
                                                }
                                                
                                        }else if(users[a]==assistant){
                                                if(activeDept==dept && userType=="orgChartAsstHead"){
                                                        //set the choice checked
                                                        users.splice(a,1,userId+"->"+userText+"->1");
                                                }
                                                if(userType!="orgChartAsstHead" || activeDept!=dept){
                                                        //replace the value to empty
                                                        users.splice(a,1,"");
                                                }
                                        }
                                        //extract the users from variable memebers in the node
                                        for(m=0;m<members.length-1;m++){
                                                //check if users is exist in the members
                                                if(users[a]==members[m]){
                                                        if(activeDept==dept && userType=="orgChartMembers"){
                                                                //set the choice checked
                                                                users.splice(a,1,userId+"->"+userText+"->1");
                                                        }
                                                        if(userType!="orgChartMembers" || activeDept!=dept){
                                                                //replace the value to empty
                                                                users.splice(a,1,"");
                                                        }
                                                }
                                        }
                                }
                        }
		})
		//extract the valid users that are not exist in the node
		for(var a=0;a<users.length-1;a++){
			userId = users[a].split("->")[0];
			userText = users[a].split("->")[1];
			userChecked = users[a].split("->")[2];
			//check if the value in array is empty
			if(userId!=""){
				//filter the users for the output then concatinate to the "display" variable
				if(containertype=="radio"){
					display+="<label><input class = 'membersDepartment' type='radio' name='userOrgchart' id='orgchartDeptUserList_"+userId+"' value='"+userId+"' text='"+userText+"' checked_attr='"+userChecked+"' "+setUserChecked(userChecked)+"> "+userText+"</label>"+"<br />";
				}else if(containertype=="checkbox"){
					display+="<label><input class = 'membersDepartment' type='checkbox' id='orgchartDeptUserList_"+userId+"' value='"+userId+"' text='"+userText+"' checked_attr='"+userChecked+"' "+setUserChecked(userChecked)+"> "+userText+"</label>"+"<br />";
				}
			}
		}
		//display the VALID user choices in the modal
                $(".userDepartment").html( display );
                //alert(url + "loadActionStatus")
        });
}

//after choosing the users in the modal, append to the specific container
function appendUserOrgchart(container){
        var nodeInit_id = $("#node_id").val().split("_")[1];
        var userType = $("#txtorgchartDeptUsers").val();
        var appendType;
        var users = "";var usersInNode = "";
        $(".membersDepartment").each(function(){
                initID = this.id.split("_")[1];
                if($(this).is(':checked')){
                        usersInNode+=$(this).val()+"->"+$(this).attr("text")+"->"+$(this).attr("checked_attr")+",";
                }
        })
        //arrange the users
        arrangeUsersOrgChart(userType,usersInNode);
        //update the json of node for(head,assistant head and members)
        var node_data =  jQuery.parseJSON($("#node_"+nodeInit_id).attr("node_data"));
        node_data[userType] = usersInNode;
        var node_dataString = JSON.stringify(node_data);
        $("#node_"+nodeInit_id).attr("node_data",node_dataString)
        //close the modal
        $(container).dialog("close");
}
//set the attribute as checked
function setUserChecked(status){
	if(status==1){
		return "checked='checked'";
	}else{
		return false;
	}
}

//Arrange users in their specific container
function arrangeUsersOrgChart(userType,usersInNode){
        var usersArray = usersInNode.split(",");
        var users = "";
        for(a=0;a<usersArray.length-1;a++){
		userId = usersArray[a].split("->")[0];
		userText = usersArray[a].split("->")[1];
                users+="<div class='membersDepartmentAppend "+userType+"_User' id='membersDepartmentAppend_"+userId+"'>"+
                                "<div class='membersDepartmentAlign'>"+
                                        "<div style='float:left;margin-top:5px;margin-left:5px;width:100px'>" + userText + "</div>"+
                                        "<div style='float:right;margin-top:5px;margin-right:5px;cursor:pointer;font-weight:bolder;font-size:10px;color:rgb(226, 173, 173)' id='remmoveMembersDept_"+userId+"' userType="+userType+" onclick='removeorgchartDeptUsers(this)'>X</div>"+
                                "</div>"+
                        "</div>";
        }
        $("."+userType).html(users);
}

//delete the user from the choices
function removeorgchartDeptUsers(obj){
        initID = obj.id.split("_")[1];
        var userType = $("#"+obj.id).attr("userType");
        var nodeInit_id = $("#node_id").val().split("_")[1];
        var node_data =  jQuery.parseJSON($("#node_"+nodeInit_id).attr("node_data"));
        deptUser = node_data[userType].split(",");
        var newDeptUsers = "";
        for(a=0;a<deptUser.length-1;a++){
		userId = deptUser[a].split("->")[0]
                if(userId!=initID){
			newDeptUsers+=deptUser[a]+",";
                }
        }
        node_data[userType] = newDeptUsers;
        var node_dataString = JSON.stringify(node_data);
        $("#node_"+nodeInit_id).attr("node_data",node_dataString)
        $("#membersDepartmentAppend_"+initID).remove();
        
}

function openSaveDialog(){
	$( "#divSave" ).dialog({
		height:250,
		width:450,
		modal:true,
		resizable:false
	});
}

//get the department from json
function getDepartment(initID){
        var node_data =  jQuery.parseJSON($("#node_"+initID).attr("node_data"));
        $(".nodeDepartment").val(node_data.dept);
};
//set the department on json and label
function setDepartment(initID,obj){
        var node_data =  jQuery.parseJSON($("#node_"+initID).attr("node_data"));
        node_data.dept = obj.value;
        var node_dataString = JSON.stringify(node_data);
        $("#node_"+initID).attr("node_data",node_dataString)
        $("#nodeLabel_"+initID).text(obj.value);
};

function saveNewOrgchart(){
	var ctrNode=0;var ctrLine = 0;//counter
	var nodes = [];var lines = [];//objects in canvas
	$(".outerNode").each(function(){
		ctrNode++;
	})
	$(".lines").each(function(){
		ctrLine++;
	})
	//validation
	if(ctrNode == 0 && ctrLine == 0){
		//empty
		alert("Empty Canvas..");
                //close the modal
                $("#divSave").dialog("close");
	}else{
		if(ctrNode==0){
			//no node
			alert("Empty Node..")
                        //close the modal
                        $("#divSave").dialog("close");
		}else if(ctrLine==0){
			//no line
			alert("Empty Line..")
                        //close the modal
                        $("#divSave").dialog("close");
		}else{
                        //other details
                        orgChartTitle = $("#orgChartTitle").val();
                        orgChartDesc = $("#orgChartDesc").val(); // description
                        orgChartStatus = $("#orgChartStatus").val();
                        if(orgChartTitle == "" || orgChartDesc ==""){
                                alert("Please complete other information")
                        }else{
                                var nodes = "";var lines = "";
                                //for nodes
                                $(".outerNode").each(function(){
                                        textId = $(this).attr("id").split("_");
                                        nodes += $(this).attr("id")+"++"+$(this).css("top")+"++"+$(this).css("left")+"++"+parseInt($("#innerNode_"+textId[1]).css("height"))+"px++"+parseInt($("#innerNode_"+textId[1]).css("width"))+"px++"+$("#nodeLabel_"+textId[1]).text()+"{}";
                                })
                                //for lines
                                $(".lines").each(function(){
                                        lines += $(this).attr("class")+"++"+$(this).attr("parent")+"++"+$(this).attr("child")+"++"+$(this).css("top")+"++"+$(this).css("left")+"++"+$(this).css("height")+"++"+$(this).css("width")+"{}";
                                })
                                
                                //ajax request
                                $.ajax({
                                url: url + "saveOrgchart/" + nodes + "/" + lines + "/" + orgChartTitle + "/" + orgChartDesc + "/" + orgChartStatus,
                                type: "POST",
                                cache: false
                                }).done(function( data ) {
                                        alert("Saved!");
                                        window.location.reload(true)
                                })
                                //remove warning on reloading the page
                                fire_onBeforeOnload(0)
                                
                        }
		}
	}
}
function setOrgchart(){
        setNodesFromDB()
        setLinesFromDB()
        //interaction of nodes
        $(".nodeContent").remove();
}
function setNodesFromDB(){
        var nodes = $(".nodesDB").text();
        var output = "";
        if(nodes!=""){
                nodes2 = nodes.split("{}");
                for(a=0;a<nodes2.length;a++){
                        if(nodes2[a]!=""){
                                unique_id = nodes2[a].split("++")[0].split("_")[1];
                                output+=setNode(unique_id,2,nodes2[a].split("++")[5],nodes2[a].split("++")[1],nodes2[a].split("++")[2],nodes2[a].split("++")[3],nodes2[a].split("++")[4],"")
                        }
                }
        }
        $("#droppable").append(output);
        nodeInteraction()
}
function setLinesFromDB(){
        var lines = $(".linesDB").text();
        var output = "";
        if(lines!=""){
                lines2 = lines.split("{}");
                for(a=0;a<lines2.length;a++){
                        if(lines2[a]!=""){
                                rel = lines2[a].split("++")[0].split(" ")[3];
                                output+=setLineIndiv(lines2[a].split("++")[0],
                                                     lines2[a].split("++")[1],
                                                     lines2[a].split("++")[2],
                                                     removePixelsExt(lines2[a].split("++")[3]),
                                                     removePixelsExt(lines2[a].split("++")[4]),
                                                     removePixelsExt(lines2[a].split("++")[5]),
                                                     removePixelsExt(lines2[a].split("++")[6]),
                                                     rel)
                        }
                }
        }
        $("#droppable").append(output);
}

function removePixelsExt(text){
        return text.substr(0,text.length-2);
}
function warningActivateOrgchart(obj){
        if(obj.value==1){
                $.ajax({
                url: "/warningOrgchartActivate/",
                cache: false
                }).done(function( data ) {
                        if(data>0){
                                alert("Warning, Your active orgchart will be deactivated");
                        }
                })
        }
}